import { OrderType } from '@/enum'
import {
  cancelOrder,
  deleteOrder,
  followDoctor,
  getPrescriptionPic
} from '@/services/consult'
import { getMedicalOrderDetail } from '@/services/order'
import { sendMobileCode } from '@/services/user'
import type { ConsultOrderItem, FollowType } from '@/types/consult'
import type { OrderDetail } from '@/types/order'
import type { CodeType } from '@/types/user'
import {
  showFailToast,
  showImagePreview,
  showSuccessToast,
  showToast,
  type FormInstance
} from 'vant'
import { onMounted, onUnmounted, ref, type Ref } from 'vue'

// 1. 关注的功能函数
export const useFollow = (type: FollowType = 'doc') => {
  const loading = ref(false)
  // 类型兼容
  const follow = async (obj: { id: string; likeFlag: 0 | 1 }) => {
    try {
      loading.value = true
      // 1.1 调用接口
      await followDoctor(obj.id, type)
      // 1.2 处理页面展示
      obj.likeFlag = obj.likeFlag === 1 ? 0 : 1
    } finally {
      loading.value = false
    }
  }
  return {
    loading,
    follow
  }
}

// 2. 查看处方
export const usePreviewPriscription = () => {
  // 2.1 查询原始处方
  const showPrescription = async (id?: string) => {
    if (id) {
      // 调用接口
      const res = await getPrescriptionPic(id)
      // 图片预览
      return showImagePreview([res.data.url])
    }
  }
  // 2.2 返回
  return {
    showPrescription
  }
}

// 3. 取消问诊订单
export const useCancelOrder = () => {
  const loading = ref(false)
  const cancelConsultOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await cancelOrder(item.id)
      // 修改状态和状态提示文字
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('订单取消操作成功')
    } catch (error) {
      showFailToast('订单取消操作失败')
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    cancelConsultOrder
  }
}

// 4. 删除问诊订单
export const useDeleteOrder = (cb: () => void) => {
  const deleteLoading = ref(false)
  const deleteConsultOrder = async (id: string) => {
    deleteLoading.value = true
    try {
      await deleteOrder(id)

      // 不同组件调用处理的业务不同
      cb && cb()

      showSuccessToast('订单删除操作成功')
    } catch (error) {
      showFailToast('订单删除操作失败')
    } finally {
      deleteLoading.value = false
    }
  }
  return {
    deleteLoading,
    deleteConsultOrder
  }
}

// 5. 获取药品订单详情
export const useOrderDetail = (id: string) => {
  const order = ref<OrderDetail>()
  onMounted(async () => {
    const res = await getMedicalOrderDetail(id)
    order.value = res.data
  })
  return {
    order
  }
}

// 6. 发送短信验证码
export const useSendMobileCode = (
  mobile: Ref<string>,
  type: CodeType = 'login'
) => {
  const formRef = ref<FormInstance>()
  const time = ref(0)
  let timerId: number
  const sendCode = async () => {
    // --------发送验证码逻辑------------
    // 4.1 判断没有在倒计时
    if (time.value > 0) return
    // 4.2 校验手机表单项
    await formRef.value?.validate('mobile')
    // 4.3 调用发送短信验证码的接口
    const res = await sendMobileCode(mobile.value, type)
    console.log(res.data.code)
    showToast(res.data.code)
    // --------倒计时逻辑------------
    time.value = 10
    // 注意点: 在事件处理函数中使用定时器一定要先清除后设置, 不然会发生定时器累加
    window.clearInterval(timerId)
    timerId = setInterval(() => {
      time.value--
      if (time.value <= 0) {
        window.clearInterval(timerId)
      }
    }, 1000)
  }
  onUnmounted(() => {
    window.clearInterval(timerId)
  })

  return {
    formRef,
    time,
    sendCode
  }
}
